package com.swgk.core;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.swgk.core.base.api.APIManager;
import com.swgk.core.base.api.AppFolwLogApi;
import com.swgk.core.base.model.entity.BehaviourFlowLog;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MLog;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import okio.Buffer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author 张驰
 * @date 2021/7/19 15:10
 * @Description 接口上报服务器工具
 * @name com.swgk.core.base.api
 */
public class FlowLogUtils {
    private Disposable disposable;

    public FlowLogUtils() {
    }

    /**
     * 各模块使用次数上报服务器
     * 启动6秒计时器，当超过六秒时，请求服务器
     */
    @SuppressLint({"AutoDispose", "CheckResult"})
    public void useModeNumToService6(int  tabSelectId) {
        boolean aBoolean = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.PrivacyAgreement, false);
        if (!aBoolean) return;
        stopTimer();
        //每隔6秒执行一次逻辑代码
        disposable = Observable.interval(6000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    toService(tabSelectId);
                });
    }

    /**
     * 停止定时执行
     */
    protected void stopTimer() {
        if (null != disposable) {
            disposable.dispose();
            disposable = null;
        }
    }

    /**
     * 用户中心各菜单栏目使用上报
     */
    protected void useSelfModeNumToService(String tabName, String module, String referer, String titleName) {
//        long timeNew = System.currentTimeMillis();
//        long timeOld = MkvUtils.get().getLong(MkvUtils.CommomData, MkvUtils.upDateTodayTime + module, 0);
//        if (!DateUtils.timestampToDate(timeNew).equals(DateUtils.timestampToDate(timeOld))){
        BehaviourFlowLog behaviourFlowLog = new BehaviourFlowLog(
                "MainActivity/SelfFragment",
                "MODULE_VISIT",
                "用户中心各菜单模块统计," + referer + "   所属栏目" + tabName + "  ： " + module + "点击模块名称 :" + titleName,
                module);
        behaviourFlowLog.setReferer(referer);
        getFlowLog(behaviourFlowLog);
//        }

    }

    /**
     * 各模块首次使用上报
     */
    protected void useModeNumToService(String module, String referer, String titleName) {
//        long timeNew = System.currentTimeMillis();
//        long timeOld = MkvUtils.get().getLong(MkvUtils.CommomData, MkvUtils.upDateTodayTime + module, 0);
//        if (!DateUtils.timestampToDate(timeNew).equals(DateUtils.timestampToDate(timeOld))){
        BehaviourFlowLog behaviourFlowLog = new BehaviourFlowLog(
                "MainActivity/HomeFragment/BigHomeFragment",
                "MODULE_VISIT",
                "大首页模块统计," + referer + "：module：" + module + "点击模块名称 :" + titleName,
                module);
        behaviourFlowLog.setReferer(referer);
        getFlowLog(behaviourFlowLog);
//        }

    }

    public void getFlowLog(BehaviourFlowLog behaviourFlowLog) {
        boolean aBoolean = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.PrivacyAgreement, false);
        if (!aBoolean) return;
        if (!"release".equals(BuildConfig.BUILD_TYPE)) return;
        String rul = BuildConfig.BASE_URL.replace("sgb-app-android/","shigongbang-analysis/v3/behaviour/flow/log");;
        behaviourFlowLog.getExtra().getOsInfo().setAppVersion("v" + getLocalVersionName(BaseAppHelper.get().getInstance()));
      /*  APIManager.getInstance().create(AppFolwLogApi.class).putBehaviourFlowLog(rul, behaviourFlowLog).enqueue(new Callback<String>() {

            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                try {
                    if (response.body() == null)
                        return;

                    MLog.d("请求成功 body:" + response.body());
                    MLog.d("请求传参 body:" + getParamContent(response.raw().request().body()));

                    //app当天第一次打开
                    if ("DAU".equals(behaviourFlowLog.getWhat())) {
                        MkvUtils.get().putLong(MkvUtils.CommomData, MkvUtils.upDateTodayTime, behaviourFlowLog.getWhen());
                    }
//                    else
                    //各模块的调用时间保存
//                    if ("MODULE_VISIT".equals(behaviourFlowLog.getWhat())){
//                        MkvUtils.get().putLong(MkvUtils.CommomData, MkvUtils.upDateTodayTime + behaviourFlowLog.getModule(), behaviourFlowLog.getWhen());
//                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
            }
        });*/
    }

    /**
     * 获取本地软件版本名称
     */
    public String getLocalVersionName(Context context) {
        String localVersion = "1.0.0";
        try {
            PackageInfo packageInfo = context.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            localVersion = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 获取常规post请求参数
     */
    private String getParamContent(RequestBody body) throws IOException {
        Buffer buffer = new Buffer();
        body.writeTo(buffer);
        return buffer.readUtf8();
    }

    public void useMySelfModeNumToService(String tabName, String titleName) {
        boolean aBoolean = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.PrivacyAgreement, false);
        if (!aBoolean) return;
        String module = "";
        if (TextUtils.isEmpty(titleName) || titleName.length() < 2) return;
        switch (titleName.substring(0, 2)) {
            case "0_": //团队常用功能
                module = "tuandui";
                break;
            case "1_": //待办
                module = "daiban";
                break;
            case "2_": //个人服务
                module = "gerenfuwu";
                break;
            case "3_": //商品经营
                module = "shangoinjingying";
                break;
            case "4_": //租赁经营
                module = "zulinjingying";
                break;
            case "5_": //工程工队
                module = "gongchenggongdui";
                break;
            case "6_": //商机管理
                module = "shangjiguanli";
                break;
            case "7_": //招采经营
                module = "zhaocaijingying";
                break;
            case "8_": //集采管理
                module = "jicaiguanli";
                break;
            case "9_": //知识分享
                module = "zhishifenxiang";
                break;
            case "10": //物流运输(货主)
            case "11": //物流运输(物流企业)
            case "12": //物流运输（车主）
            case "13": //物流运输(加油站)
                module = "wuliuyunshu";
                break;
            case "14": //会员经营
                module = "huiyuanjingying";
                break;
            case "15": //网站建设
                module = "wangzhanjianshe";
                break;
            case "16": //团队管理
                module = "tuanduiguanli";
                break;
            case "17": //智能关注
                module = "zhinengguanzhu";
                break;
            case "18": //企业设置
                module = "qiyeshezhi";
                break;
            case "19": //账户配置
                module = "zhanghupeizhi";
                break;
            case "20": //团队管理
                module = "tuanduguanli";
                break;
            case "23": //资金中心
                module = "zijinzhongxin";
                break;
        }
        useSelfModeNumToService(tabName, module, "点击用户中心菜单Menu直接调用", titleName);
    }

    /**
     * tab点击停留超过6秒调用接口
     *
     * @param tabSelectId
     */
    protected void toService(int tabSelectId) {
        stopTimer();
        String module = "";
        if (tabSelectId == 2) { //招采
            module = "zhaocai";
        } else if (tabSelectId == 1) { //商品
            module = "shangpin";
        } else if (tabSelectId == 3) { //集采
            module = "jicai";
        } else if (tabSelectId == 4 ) { //租赁
            module = "zulin";
        } else if (tabSelectId == 5) { //工队
            module = "gongdui";
        } else if (tabSelectId == 6) { //物流
            module = "wuliu";
        } else if (tabSelectId == 22) { //企业服务
            module = "qifu";
        } else if (tabSelectId == 24) { //会员
            module = "huiyuan";
        } else if (tabSelectId == 23) { //企业经营
            module = "qiye";
        } else if (tabSelectId == 27) { //招商引资
            module = "zhaoshang";
        } else if (tabSelectId == 31){ //吃住行
            module = "chizhuxing";
        } else if (tabSelectId == 21) { //大首页
            module = "dashouye";
        }
        useModeNumToService(module, "点击Tab,用户停留超过6秒时，上报接口服务器", module);
    }

    /**
     * 直接调用，统计各模块的点击次数
     *
     * @param titleName
     */
    public void useModeNumToService(String titleName) {
        boolean aBoolean = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.PrivacyAgreement, false);
        if (!aBoolean) return;
        String module = "";
        switch (titleName) {
            case "商品材料":
            case "自营商品":
            case "集采商品":
                module = "shangpin";
                break;
            case "会员经营":
                module = "huiyuan";
                break;
            case "招标大厅":
            case "直接竞价":
                module = "zhaocai";
                break;
            case "需方集采":
            case "供方集采":
                module = "jicai";
                break;
            case "货运大厅":
            case "货车大厅":
            case "竞价找车":
            case "竞价找货":
                module = "wuliu";
                break;
            case "出租大厅":
            case "求租大厅":
            case "集采租赁":
            case "转让大厅":
                module = "zulin";
                break;
            case "工程工队":
            case "工种报价":
            case "临时用工":
            case "工程分包":
                module = "gongdui";
                break;
            case "服务大厅":
            case "工商服务":
            case "知产服务":
            case "资质服务":
                module = "qifu";
                break;
        }
        useModeNumToService(module, "点击首页菜单栏目Menu直接调用", titleName);
    }
}
